package goldgame;
import java.awt.*;

/**
 * A view Component suitable for inclusion in an AWT Frame.
 * Paints itself by consulting its model.
 */
public class GameView extends Canvas {

	/** Size of game model */
	private Dimension modelSize;

	/** Size of every tile in the model */
	private Dimension tileSize;

	/** The game model which is drawn */
	private GameModel model;

	/** The offscreen buffer */
	private Graphics offscreenGraphics;

	/** Image representing the offscreen graphics */
	private Image offscreenImage;
	
	/**
	 * Creates a view where each GameObject has side length 20 pixels..
	 */
	public GameView() {
		this(20);
	}
	
	/**
	 * Creates a view where each GameObject has a given size.
	 * @param tileSide  side length in pixels of each GameObject.
	 */
	public GameView(int tileSide) {
		tileSize = new Dimension(tileSide, tileSide);
		modelSize = GameFactory.getGameSize();
		setSize(
			modelSize.width * modelSize.width,
			modelSize.height * modelSize.height);
	}
	
	/** 
	 * Updates the view with a new model.
	 */
	public void setModel(GameModel model) {
		this.model = model;
		repaint();
	}
	

	/**
	 * This method ensures that the painting
	 * is performed double-buffered. This means
	 * there won't be any flicker when repainting
	 * all the time.
	 */
	public void update(Graphics g) {
		// Create an offscreen buffer (if we don't have one)
		if (offscreenImage == null) {
			Dimension size = getSize();

			offscreenImage = createImage(size.width, size.height);
			offscreenGraphics = offscreenImage.getGraphics();
		}

		// This will invoke painting correctly on the offscreen buffer
		super.update(offscreenGraphics);
		
		// Draw the contents of the offscreen buffer to screen.
		g.drawImage(offscreenImage, 0, 0, this);
	}


	/** 
	 * Consults the model to paint the game matrix.
	 * If model is null, draws a default text.
	 */
	public void paint(Graphics g) {
		// Check if we have a running game
		if (model != null) {
			
			// Draw all tiles by going over them x-wise and y-wise.
			for(int i = 0; i < modelSize.width; i++) {
				for(int j = 0; j < modelSize.height; j++) {
					GameTile tile = model.getGameboardState(i, j);
					tile.draw(
						g,
						i * tileSize.width,
						j * tileSize.height,
						tileSize);
				}
			}
		}
	}
}



